//
//  JWSound.m
//  KotH
//
//  Created by James Weatherley on 14/01/2010.
//  Copyright 2010 James Weatherley. All rights reserved.
//

#import "JWSound.h"


@implementation JWSound

static JWSound* s_sound = 0;

-(id)init
{
	assert(!s_sound);
	self = [super init];
	if(self) {
		
		NSArray* soundFiles = [NSArray arrayWithObjects:@"absorb", @"meanie", @"probe", @"teleport", @"create", nil];
		sounds = [[NSMutableDictionary alloc] initWithCapacity:[soundFiles count]];
		NSString* mp3Path = nil;
		
		for(NSString* soundFile in soundFiles) {
			mp3Path = [[NSBundle mainBundle] pathForResource:soundFile ofType:@"mp3"];
			assert(mp3Path);
			
			AVAudioPlayer* player = [[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:mp3Path] error:nil] autorelease];
			player.delegate = self;
			[player prepareToPlay];
			[sounds setObject:player forKey:soundFile];
		}
		mute = NO;
	}

	return self;
}

-(void)dealloc
{
	[sounds release];
	[super dealloc];
}

#pragma mark Sound methods
+(JWSound*)soundManager
{
	if(!s_sound) {
		s_sound = [[JWSound alloc] init];
	}
	return s_sound;
}

-(void)playSound:(NSString*)sound
{
	if(!mute) {
		AVAudioPlayer* player = [sounds objectForKey:sound];
		if(player.playing) {
			[player stop];
		}
		[player play];
	}
}

-(BOOL)playingSound:(NSString*)sound
{
	AVAudioPlayer* player = [sounds objectForKey:sound];
	return player.playing;
}

-(void)stopSound:(NSString*)sound
{
	AVAudioPlayer* player = [sounds objectForKey:sound];
	[player stop];
	player.currentTime = 0;
	[player prepareToPlay];
}

-(void)stopAllSounds
{
	for(NSString* sound in sounds) {
		[self stopSound:sound];
	}
}

-(void)muteSounds:(BOOL)m
{
	mute = m;
}

-(BOOL)muted
{
	return mute;
}

#pragma mark Delegate methods
-(void)audioPlayerEndInterruption:(AVAudioPlayer*)player
{
	[player play];
}

@end
